<?php
require_once('lib/src/config.php');
require_once('lib/src/apiClient.php');
require_once('lib/src/contrib/apiCalendarService.php');

$calID = 'stanley5.com_p13b36incoflgq8076i6lvqk0k@group.calendar.google.com';  //Family Tree

function formatName ($first, $middle, $last, $suffix, $nick, $items)
{
	$formatName = "";
	if (strpos($items, "f") !== FALSE && $first != "") {
		$formatName .= "$first ";  }
	if (strpos($items, "n") !== FALSE && $nick != "") {
		$formatName .= "($nick) ";  }
	if (strpos($items, "m") !== FALSE && $middle != "") {
		$formatName .= "$middle ";  }
	if (strpos($items, "l") !== FALSE && $last != "") {
		$formatName .= "$last";  }
	if (strpos($items, "s") !== FALSE && $suffix != "") {
		$formatName .= ", $suffix ";  }
	return $formatName;
}

function ClearGCal()
{
	global $calID, $apiclient, $service, $token;
	
	//Looks like clear doesn't work for secondary calendars
	//Clears a primary calendar. This operation deletes all data associated 
	//with the primary calendar of an account and cannot be undone.
	
	/* Generates this error if you try:
	
	[Thu Mar 08 19:11:22 2012] [error] [client 71.187.52.123] PHP Fatal error:  Uncaught exception 'apiServiceException' with message 'Error calling POST https://www.googleapis.com/calendar/v3/calendars/stanley5.com_p13b36incoflgq8076i6lvqk0k@group.calendar.google.com/clear?key=AIzaSyCKLKK3MGdaMUmIfwth0_0kNIQ5JCqA35w: (400) Invalid Value' in /opt/csw/apache2/share/htdocs/www/secure/ftree/gcal/lib/src/io/apiREST.php:86
	Stack trace:
	#0 /opt/csw/apache2/share/htdocs/www/secure/ftree/gcal/lib/src/io/apiREST.php(56): apiREST::decodeHttpResponse(Object(apiHttpRequest))
	#1 /opt/csw/apache2/share/htdocs/www/secure/ftree/gcal/lib/src/service/apiServiceResource.php(187): apiREST::execute(Object(apiServiceRequest))
	#2 /opt/csw/apache2/share/htdocs/www/secure/ftree/gcal/lib/src/contrib/apiCalendarService.php(260): apiServiceResource->__call('clear', Array)
	#3 /opt/csw/apache2/share/htdocs/www/secure/ftree/gcal/add_all_dobs.php(28): CalendarsServiceResource->clear('stanley5.com_p1...')
	#4 /opt/csw/apache2/share/htdocs/www/secure/ftree/gcal/add_all_dobs.php(102): ClearGCal()
	#5 {main}
	  thrown in /opt/csw/apache2/share/htdocs/www/secure/ftree/gcal/lib/src/io/apiREST.php on line 86
  
	*/
	
	$service->calendars->clear($calID);

}

function AddToGCal ($name, $DOB, $URL)
{
	global $calID, $apiclient, $service, $token;
	
	if ($DOB == "0000-00-00" or $DOB == "") { return(""); }
	
	//Date functions can't handle pre-7/2/1970 and Google can't handle pre-1900
	//So we'll just enter the first event in the current year, date("Y")
	
	$dobElements = explode("-",$DOB);
	$bSt =  mktime(0,0,0,$dobElements[1],$dobElements[2],date("Y"));
	$bEnd = mktime(0,0,0,date("n",$bSt),date("j",$bSt)+1,date("Y")); //this will handle probs like 12/31 + 1
	$startDate = date("Y-m-d", $bSt);
	$endDate = date("Y-m-d", $bEnd);
	print("$startDate to $endDate\n");
	
	//  CREATE EVENT

	$event = new Event();

	$event->setSummary("$name ($dobElements[0])");

	$stDT = new EventDateTime();
	$stDT->setDate("$startDate");  //use setDate for date property, setDateTime for dateTime property
	$stDT->setTimeZone('America/New_York'); //must set a timezone for a recurring event (?)
	$event->setStart($stDT);
	$endDT = new EventDateTime();
	$endDT->setDate("$endDate");
	$endDT->setTimeZone('America/New_York');
	$event->setEnd($endDT);

	$event->setRecurrence(array('RRULE:FREQ=YEARLY'));
	
	$event->setDescription($URL);

	print_r($event);

	$newEvent = $service->events->insert($calID, $event);

	$gcalID = $newEvent->getID();
	//$gcalID = 'r3brn59baugkcm41flglps87ok';
	return($gcalID);
}

$urlRoot = "http://".$_SERVER['SERVER_NAME']."/secure/ftree/";

session_start();

//  AUTHENITCATE TO GOOGLE

$apiClient = new apiClient();
$apiClient->setUseObjects(true);
$service = new apiCalendarService($apiClient);

if (isset($_SESSION['oauth_access_token'])) {
  $apiClient->setAccessToken($_SESSION['oauth_access_token']);
} else {
  $token = $apiClient->authenticate();
  $_SESSION['oauth_access_token'] = $token;
}

// CONNECT TO DB

$link = mysql_connect("localhost", "ftreemod", "ftree_mod")
   or die("Could not connect : " . mysql_error());
mysql_select_db("ftree",$link) or die("Could not select database");

$query = "SELECT * FROM person WHERE `dob` IS NOT NULL AND `dob` <> '0000-00-00' ORDER BY `dob` ASC";
$result = mysql_query($query,$link) or die("Get persons query failed : " . mysql_error());

//ClearGCal();

// COMMENTED OUT - DANGER WILL ROBINSON - WE DON'T WANT TO RUN THIS AGAIN BY MISTAKE!

print("<p><b>The main procedure has been commented out to prevent accidentally adding all of the entries again.</b></p>\n");

/*
print("<pre>\n");

while ($person = mysql_fetch_array($result, MYSQL_ASSOC)) {

	$full = formatName($person['first'], $person['middle'], $person['last'], $person['suffix'], $person['nick'], "fmls");
	$dob = $person['dob'];
	$id = $person['id'];
	$url = "${urlRoot}main.php?view=detail&id=$id";
	
	$gCalID = AddToGCal($full,$dob,$url);

	print("$full $dob $gCalID $url\n");
	
	$update = "UPDATE `person` SET `gcalID` = '".$gCalID."' WHERE `id` = $id";
	print("$update\n");
	$updResult = mysql_query($update) or die("Person update with gcalID failed: " . mysql_error());
}

print("</pre>\n");
*/
mysql_close($link);


?>